//---------------------------------------------------------------------------
/**
 * \class CLock
 * \brief This is a class for locking a file exclusively 
 * \version 0.1
 *
 * \author Woo-Hyun Kim (woorung@nhncorp.com, woorung@gmail.com)
 * \author http://blog.naver.com/wisereign .
 *
 * \date 2008/10/13
 */
//---------------------------------------------------------------------------
#include "CLock.h"
//---------------------------------------------------------------------------
CLock::CLock()
{
	is_lock = false;
	status = 0;

	lock_fp = fopen(DEFAULT_LOCK_FILE, "a+b");
	lock_fd = fileno(lock_fp);
}
//--------------------------------------------------------------------------
CLock::CLock(const char *lckf)
{
	is_lock = false;
	status = 0;

	lock_fp = fopen(lckf, "a+b");
	lock_fd = fileno(lock_fp);
}
//--------------------------------------------------------------------------
CLock::~CLock()
{
	fclose(lock_fp);
}
//--------------------------------------------------------------------------
int CLock::lock()
{
#ifdef USE_LOCKF
	status = lockf(lock_fd, F_LOCK, 0);
#else
	struct flock file_lock;
	file_lock.l_type = F_WRLCK;
	file_lock.l_whence = SEEK_SET;
	file_lock.l_start = 0;
	file_lock.l_len = 0;

	status = fcntl(lock_fd, F_SETLKW, &file_lock);
#endif

	if(status!=0) is_lock = false;
	else is_lock = true;

	return status;
}
//--------------------------------------------------------------------------
int CLock::unlock()
{
#ifdef USE_LOCKF
	status = lockf(lock_fd, F_ULOCK, 0);
#else
	struct flock file_lock;
	file_lock.l_type = F_UNLCK;
	file_lock.l_whence = SEEK_SET;
	file_lock.l_start = 0;
	file_lock.l_len = 0;

	status = fcntl(lock_fd, F_SETLK, &file_lock);
#endif

	if(status!=0) is_lock = true;
	else is_lock = false;

	return status;
}
//--------------------------------------------------------------------------
